﻿using System;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
using Commons.Xml.Relaxng;
using Newtonsoft.Json.Schema;

namespace XmlRuleBuilder
{
    class Program
    {
        static class RuleFile
        {
            public const string Path = @"..\..\..\..\src\XmlRules\bin\debug";

            static class RuleCategory
            {
                public const string Common = "Common";
                public const string MetadataDocument = "MetadataDocument";
                public const string ServiceDocument = "ServiceDocument";
                public const string Feed = "Feed";
                public const string Entry = "Entry";
            }
            
            // This is rule under development
            public const string Category = RuleCategory.Entry;
            public const string Name = "Entry.Core.1012.xml";
        }

        static void Main(string[] args)
        {
            // Set Macros if there's any being used
            Macro macro = new Macro("Categories", "", "http://raeda5iis/NorthwindFKLess/Northwind.svc/Categories(1)", "");

            string ruleXml = Path.Combine(Path.Combine(RuleFile.Path, RuleFile.Category), RuleFile.Name);
            string mdXml = "Sample.Metadata.xml";
            XmlDocument xmlDoc = new XmlDocument();
            bool isXmlValid = false;

            try
            {
                xmlDoc.Load(ruleXml);
                isXmlValid = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Rule XML instance is invalid : {0}", ex.Message));
            }

            if (isXmlValid)
            {
                XmlNode node;
                XmlElement root = xmlDoc.DocumentElement;
                node = root.SelectSingleNode("/rules/rule/action");

                switch (node.Attributes["processor"].Value)
                {
                    case "rng":
                    case "xslt+rng":
                        ATOMValidator.Validate(node, mdXml, macro);
                        break;
                    case "jsonschema":
                    case "xslt+jsonschema":
                        JSONValidator.Validate(node, mdXml, macro);
                        break;
                    default:
                        Console.WriteLine("Invalid input processor type!");
                        break;
                }
            }

            Console.ReadKey();
        }
    }
}
